package cn.imnaer.service.rpc.location;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Generated;

import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import org.bson.types.BasicBSONList;

import cn.imnaer.database.BaseDao;
import cn.imnaer.database.MatchConst;
import cn.imnaer.database.define.DBConstant;
import cn.imnaer.service.persistence.model.City;
import cn.imnaer.service.persistence.model.consts.CITY;
import cn.imnaer.service.persistence.model.consts.SCENIC;
import cn.imnaer.service.rest.view.model.Place;

public class CityDaoImpl extends BaseDao<City> {
	private static CityDaoImpl instance = new CityDaoImpl();

	private CityDaoImpl() {

	}

	public static CityDaoImpl getInstance() {
		return instance;
	}

	@Override
	protected String getDbSpaceName() {
		return DBConstant.SPACE.PLACE_INFO_SPACE;
	}

	@Override
	protected String getDbCollectionName() {
		return DBConstant.COLLECTION.CITY_INFO_COLLECTION;
	}

	@Override
	protected String getPrimaryKey() {

		return null;
	}

	public City getByCityCode(String cityCode) {
		City target = null;
		BasicBSONObject matcher = new BasicBSONObject();
		matcher.put(CITY.cityCode, cityCode);
        target = this.findOne(matcher, null);
		return target;
	}

    public List<City> findByStateCode(String stateCode) {
        BasicBSONObject matcher = new BasicBSONObject();
        matcher.put(CITY.stateCode, stateCode);
        List<City> citys = this.findAll(matcher, new BasicBSONObject());
        return citys;
    }

	public List<Place> search(String keywords) {
		BSONObject selectorBson = new BasicBSONObject();
		try {
			selectorBson = BasicBSONObject.typeToBson(new City());
			if (keywords != null && !keywords.isEmpty()) {
				BSONObject matcherOne = new BasicBSONObject();
				BasicBSONList arr = new BasicBSONList();
				BSONObject parmasOne = new BasicBSONObject();
				matcherOne.put(MatchConst._REGEX, keywords);
				matcherOne.put(MatchConst._OPTIONS, "i");
				parmasOne.put("pinyin", matcherOne);
				arr.add(parmasOne);
				BSONObject parmasTwo = new BasicBSONObject();
				parmasTwo.put(CITY.cityName, keywords);
				arr.add(parmasTwo);
				BSONObject query = new BasicBSONObject();
				query.put(MatchConst._OR, arr);
				List<City> record = this.findAll(query, null);
				ArrayList<Place> places = new ArrayList<>(record.size());
				for (City city : record) {
					Place place = new Place();
					place.setAttribute(city);
					query.put(SCENIC.cityCode, city.getCityCode());
					place.setScenicCount(this.count(query));
					places.add(place);
				}
				return places;

			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;
	}

	public int getScenicCount(String cityCode) {

		return 0;

	}

}
